package com.dfdchem.imd.kaiwu.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.dfdchem.imd.kaiwu.R;
import com.dfdchem.imd.kaiwu.activity.base.BaseActivity;
import com.dfdchem.imd.kaiwu.adapter.SysMessageAdapter;
import com.dfdchem.imd.kaiwu.adapter.UserMessageAdapter;
import com.dfdchem.imd.kaiwu.constant.RouterPath;
import com.dfdchem.imd.kaiwu.interfaces.OnHttpResponseListener;
import com.dfdchem.imd.kaiwu.interfaces.RecyclerItemClickListener;
import com.dfdchem.imd.kaiwu.manager.DataManager;
import com.dfdchem.imd.kaiwu.model.MessageModel;
import com.dfdchem.imd.kaiwu.model.Resp;
import com.dfdchem.imd.kaiwu.model.SysMessageVo;
import com.dfdchem.imd.kaiwu.model.User;
import com.dfdchem.imd.kaiwu.model.UserMessageVo;
import com.dfdchem.imd.kaiwu.util.JSON;
import com.dfdchem.imd.kaiwu.util.Log;
import com.dfdchem.imd.kaiwu.util.RequestUtil;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.constant.RefreshState;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import org.jetbrains.annotations.NotNull;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;


@Route(path = RouterPath.MESSAGE_ACTIVITY)
public class MessageActivity extends BaseActivity implements View.OnClickListener, OnHttpResponseListener, OnRefreshListener {
    private static final String TAG = "MessageActivity";

    private Button text_contact_1;
    private SmartRefreshLayout refreshLayout;

    private RecyclerView sys_message_recyclerView;
    private RecyclerView user_message_recyclerView;

    private SysMessageAdapter sysMessageAdapter;
    private UserMessageAdapter userMessageAdapter;

    private TextView no_message_tips;
    private LinearLayout message_layout;
    private LinearLayout message_layout_sys;
    private LinearLayout message_layout_user;

    private Timer mTimer;

    private final static int request_code_get_message = 4;
    private final static int request_code_get_sys_message = 5;
    private final static int request_code_get_user_message = 6;

    /**
     * 启动这个Activity的Intent
     * @param context
     * @return Intent
     */
    public static Intent createIntent(Context context) {
        return new Intent(context, MessageActivity.class);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_message);

        initView();
        initData();
        initEvent();
    }

    @Override
    public void initView() {
        Log.d(TAG, this.getClass().getSimpleName() + " initView");

        text_contact_1 = findViewById(R.id.text_contact_1);

        refreshLayout = findViewById(R.id.refreshLayout);

        no_message_tips = findView(R.id.no_message_tips);
        message_layout = findView(R.id.message_layout);
        message_layout.setVisibility(View.GONE);
        message_layout_sys = findView(R.id.message_layout_sys);
        message_layout_user = findView(R.id.message_layout_user);

        // 系统消息
        sys_message_recyclerView = findView(R.id.sys_message_recyclerView);

        LinearLayoutManager lm1 = new LinearLayoutManager(this){
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        DividerItemDecoration did1 = new DividerItemDecoration(sys_message_recyclerView.getContext(),
                lm1.getOrientation());
        did1.setDrawable(getDrawable(R.drawable.profile_list_divider));

        sys_message_recyclerView.setHasFixedSize(true);
        sys_message_recyclerView.setNestedScrollingEnabled(false);
        sys_message_recyclerView.setLayoutManager(lm1);
        sysMessageAdapter = new SysMessageAdapter(this);
        sys_message_recyclerView.setAdapter(sysMessageAdapter);
        sys_message_recyclerView.addItemDecoration(did1);

        // 用户消息
        user_message_recyclerView = findView(R.id.user_message_recyclerView);

        LinearLayoutManager lm2 = new LinearLayoutManager(this){
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        DividerItemDecoration did2 = new DividerItemDecoration(user_message_recyclerView.getContext(),
                lm2.getOrientation());
        did2.setDrawable(getDrawable(R.drawable.profile_list_divider));

        user_message_recyclerView.setHasFixedSize(true);
        user_message_recyclerView.setNestedScrollingEnabled(true);
        user_message_recyclerView.setLayoutManager(lm2);
        userMessageAdapter = new UserMessageAdapter(this);
        user_message_recyclerView.setAdapter(userMessageAdapter);
        user_message_recyclerView.addItemDecoration(did2);
    }

    @Override
    protected void onResume() {
        Log.d(TAG, this.getClass().getSimpleName() + " onResume");
        super.onResume();

        if (mTimer == null) {
            mTimer = new Timer();
            TimerTask mTimerTask = new TimerTask() {//创建一个线程来执行run方法中的代码
                @Override
                public void run() {
                    getMessage();
                }
            };
            mTimer.scheduleAtFixedRate(mTimerTask, 0, 1000);
        }
    }

    @Override
    protected void onDestroy() {
        Log.d(TAG, "onDestroy");
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
        super.onDestroy();
    }

    @Override
    protected void onPause() {
        Log.d(TAG, "onDestroy");
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
        super.onPause();
    }

    @SuppressLint("DefaultLocale")
    @Override
    public void initData() {
        Log.d(TAG, this.getClass().getSimpleName() + " initData");
        showProgressDialog("正在加载...");
    }

    private void getMessage(){
        Log.d(TAG, "getMessage");
        runThread(TAG + "getMessage", new Runnable() {
            @Override
            public void run() {
                RequestUtil.get_message(request_code_get_message, MessageActivity.this);
            }
        });
    }

    @Override
    public void initEvent() {
        Log.d(TAG, this.getClass().getSimpleName() + " initEvent");

        text_contact_1.setOnClickListener(this);
        refreshLayout.setOnRefreshListener(this);

        sys_message_recyclerView.addOnItemTouchListener(
                new RecyclerItemClickListener(context, sys_message_recyclerView ,new RecyclerItemClickListener.OnItemClickListener() {
                    @Override public void onItemClick(View view, int position) {
                        if (position < 0 || position > sysMessageAdapter.getMessages().size()) {
                            return;
                        }
                        SysMessageVo message = sysMessageAdapter.getMessages().get(position);
                        User user = message.getFromUser();
                        if (user == null || user.getId() <= 0) {
                            showShortToast("参数错误，请重试");
                            return;
                        }
                        ARouter.getInstance()
                                .build(RouterPath.MESSAGE_DETAIL_ACTIVITY)
                                .withInt("MESSAGE_TYPE", MessageDetailActivity.MESSAGE_TYPE_SYS)
                                .withObject("fromUser", user)
                                .navigation(MessageActivity.this);
                    }

                    @Override public void onLongItemClick(View view, int position) {
                        Log.d(TAG, "addOnItemTouchListener onLongItemClick");
                    }
                })
        );

        user_message_recyclerView.addOnItemTouchListener(
                new RecyclerItemClickListener(context, user_message_recyclerView ,new RecyclerItemClickListener.OnItemClickListener() {
                    @Override public void onItemClick(View view, int position) {
                        if (position < 0 || position > userMessageAdapter.getMessages().size()) {
                            return;
                        }
                        UserMessageVo message = userMessageAdapter.getMessages().get(position);
                        User fromUser = message.getFromUser();
                        // 兼容测试模式，即 to 为 0 的消息(发送为所有用户)
                        User toUser = DataManager.getInstance().getUser();
                        if (fromUser.getId() == toUser.getId()) {
                            fromUser = message.getToUser();
                        }
                        if (fromUser == null || fromUser.getId() <= 0 || toUser == null || toUser.getId() <= 0) {
                            showShortToast("参数错误，请重试");
                            return;
                        }
                        ARouter.getInstance()
                                .build(RouterPath.MESSAGE_DETAIL_ACTIVITY)
                                .withInt("MESSAGE_TYPE", MessageDetailActivity.MESSAGE_TYPE_USER)
                                .withObject("fromUser", fromUser)
                                .withObject("toUser", toUser)
                                .navigation(MessageActivity.this);
                    }

                    @Override public void onLongItemClick(View view, int position) {
                        Log.d(TAG, "addOnItemTouchListener onLongItemClick");
                    }
                })
        );
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.text_contact_1:
                toActivity(RouterPath.CONTACT_ACTIVITY);
                break;
        }
    }

    @Override
    public void onHttpResponse(int requestCode, String resultJson, Exception e) {
        if (requestCode == request_code_get_message) {
            dismissProgressDialog();
        }
        if (e != null) {
            Toast.makeText(getActivity(), "请求失败，" + e.getMessage(), Toast.LENGTH_LONG).show();
            return;
        }
        switch (requestCode) {
            case request_code_get_message:
                Resp<MessageModel> resp = JSON.parseResp(resultJson, MessageModel.class);
                if (resp == null || resp.getCode() != 200 || resp.getData() == null) {
                    Toast.makeText(this, resp != null ? resp.getMsg() : "请求失败，请重试", Toast.LENGTH_SHORT).show();
                    if (refreshLayout.getState() == RefreshState.Refreshing) {
                        refreshLayout.finishRefresh(250);
                    }
                    return;
                }

                List<SysMessageVo> sysMessageVos = resp.getData().getSysMessages();
                if (sysMessageVos != null && sysMessageVos.size() > 0) {
                    sysMessageAdapter.setMessages(sysMessageVos);
                    sysMessageAdapter.notifyDataSetChanged();

                    message_layout_sys.setVisibility(View.VISIBLE);
                } else {
                    message_layout_sys.setVisibility(View.GONE);
                }

                List<UserMessageVo> userMessageVos = resp.getData().getUserMessages();
                if (userMessageVos != null && userMessageVos.size() > 0) {
                    userMessageAdapter.setMessages(userMessageVos);
                    userMessageAdapter.notifyDataSetChanged();
                    message_layout_user.setVisibility(View.VISIBLE);
                } else {
                    message_layout_user.setVisibility(View.GONE);
                }

                if ((sysMessageVos == null || sysMessageVos.size() == 0) && (userMessageVos == null || userMessageVos.size() == 0)) {
                    message_layout.setVisibility(View.GONE);
                    no_message_tips.setVisibility(View.VISIBLE);
                } else {
                    message_layout.setVisibility(View.VISIBLE);
                    no_message_tips.setVisibility(View.GONE);
                }

                refreshLayout.finishRefresh(250);
                break;

        }
    }

    @Override
    public void onRefresh(@NotNull RefreshLayout refreshlayout) {
        getMessage();
    }
}